import React, {Component, Suspense} from 'react';
import {Row, Col, Icon, Menu, Dropdown} from 'antd';

import GridContent from '@/components/PageHeaderWrapper/GridContent';
import {getTimeDistance} from '@/utils/utils';

import styles from './Analysis.less';
import PageLoading from '@/components/PageLoading';
import {connect} from "react-redux";
import {FETCH_DATA, FETCH_RUNNING_DATA} from "../../models/dashboard/const";
import {getDate, getDateValue} from "../../utils/utils";
import {FETCH_DEVICES} from "../../models/device/const";
import {OFFLINE, ONLINE, RUNNING} from "../../config/const";
import getDeviceList from "../../models/selectors";
import {CHANGE_QUERY_TIME} from "../../models/report/const";
const DeviceDataCard = React.lazy(() => import('./DeviceDataCard'));
const RunningDataCard = React.lazy(() => import('./RunningDataCard'));

const ALL = 3;
@connect(({loading, dashboard, device,}) => {
  return ({
    loading: loading.fetchDashboard,
    dashboardData: dashboard,
    deviceList: getDeviceList(device),
  })
})

class Analysis extends Component {
    constructor(props) {
        super(props);
        this.state = {
            rangePickerValue: getTimeDistance('year'),
            datePickerValue: getDateValue(),
            dateType: '7days'
        };
        const {dispatch} = this.props;
        dispatch({
            type: FETCH_DEVICES,
        });
    }
    componentDidMount() {
        const {dispatch} = this.props;
        const {datePickerValue, dateType} = this.state;
        const values = getTimeDistance(dateType, datePickerValue);

        const start_time = parseInt(values[0].valueOf() / 1e3);
        const end_time = parseInt(values[1].valueOf() / 1e3);

        const payload = {start_time, end_time,};
        dispatch({
            type: FETCH_DATA,
            payload,
        });
    }

    //
    // handleRangePickerChange = rangePickerValue => {
    //   this.setState({
    //     rangePickerValue,
    //   });
    //   this.fetchRunningData(rangePickerValue)
    // };


    selectDate = type => {
        this.setState({
            dateType: type,
        }, () => {
            this.fetchRunningData()
        });
    };

    fetchRunningData = () => {
        const {dispatch} = this.props;
        const {datePickerValue, dateType} = this.state;

        const values = getTimeDistance(dateType, datePickerValue);

        const start_time = parseInt(values[0].valueOf() / 1e3);
        const end_time = parseInt(values[1].valueOf() / 1e3);
        dispatch({
            type: FETCH_RUNNING_DATA,
            payload: {start_time, end_time},
        });
    };

    isActive = type => {
        const {dateType} = this.state;
        if (type !== dateType) {
            return '';
        }
        if (
            type === dateType
        ) {
            return styles.currentDate;
        }
        return '';
    };

    batteryDataFormat = data => {
        if (!data) return [];
        return Object.keys(data).sort().slice(-30).map(item => ({
            x: item, y: data[item],
        }))
    };

    handleDatePickerChange = datePickerValue => {
        this.setState({
            datePickerValue,
        }, () => {
            this.fetchRunningData()
        });
    };

    handleChangeQueryTime = ()=>{
        const {dispatch, dashboardData: {end_time, start_time}} = this.props
        dispatch({type:CHANGE_QUERY_TIME, payload:{start_time, end_time}})
    }

    render() {
        const {loading, dashboardData, deviceList, history, dispatch} = this.props;
        const {rangePickerValue, datePickerValue} = this.state;

      if (!deviceList) return (<PageLoading/>);

        const {
            [OFFLINE]: offline_device_total,
            [ONLINE]: online_device_total,
            [RUNNING]: running_device_total,
            [ALL]: device_total,
        } = deviceList.reduce((obj, item) => (obj[item.status]++, obj[ALL]++, obj), {
            [OFFLINE]: 0,
            [ONLINE]: 0,
            [RUNNING]: 0,
            [ALL]: 0,
        });

        const {
            query_days,
            end_time,
            duration_total,
            stay_time,
            start_time,
            mileage_total,
            battery_low_record,
            mileage_total_record,
            stay_time_record,
            duration_total_record,
            current_date,
        } = dashboardData;

        const current_running_device_total = online_device_total + running_device_total;
        const device_usage_rate = (current_running_device_total / device_total * 100).toFixed(2);
        const devicePieData = [
            // {x: "设备总数 ", y: device_total},
            {x: "行驶设备数", y: running_device_total},
            {x: "停驻设备数", y: online_device_total},
            {x: "离线设备数", y: offline_device_total},
        ];
        const deviceData = {
            device_total,
            device_usage_rate,
        };

        const current_battery_low = (battery_low_record && battery_low_record[current_date]) || 0;
        const runningData = {
            query_days,
            current_running_device_total,
            running_device_total,
            mileage_total,
            duration_total,
            stay_time,
            mileage_total_record,
            stay_time_record,
            duration_total_record,
        };

        return (
            <GridContent>
                <Suspense fallback={<PageLoading/>}>
                    <DeviceDataCard
                      datePickerValue={datePickerValue}
                      handleDatePickerChange={this.handleDatePickerChange}
                      isActive={this.isActive}
                      loading={loading}
                      current_battery_low={current_battery_low}
                      devicePieData={devicePieData}
                      deviceData={deviceData}
                      batteryLowRecord={this.batteryDataFormat(battery_low_record)}
                      history={history}
                      onChangeQueryTime={this.handleChangeQueryTime}
                    />
                </Suspense>
                <Suspense fallback={null}>
                    <RunningDataCard
                      rangePickerValue={rangePickerValue}
                      runningData={runningData}
                      isActive={this.isActive}
                        // handleRangePickerChange={this.handleRangePickerChange}
                      loading={loading}
                      selectDate={this.selectDate}
                      history={history}
                      onChangeQueryTime={this.handleChangeQueryTime}
                    />
                </Suspense>
            </GridContent>
        );
    }
}

export default Analysis;
